package cn.chess.util;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;


public class AppointmentTask {
    //使用到期时间
    private LocalDateTime appointmentTime;
    //任务名称
    private String taskName;
    //
    private Timer timer;
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(20);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
    public AppointmentTask(Date appointmentTime, String taskName) {
        ZoneId zoneId = ZoneId.systemDefault();
        this.appointmentTime =    LocalDateTime.ofInstant(appointmentTime.toInstant(), zoneId);

//       LocalDateTime.parse(appointmentTime, formatter);
        this.taskName = taskName;
    }

    public void schedule() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                //提示消息（提前十分钟提示）
//                TODO 提示消息
                System.out.println("提示消息");
                timer.cancel();
            }
        },
        // 提前十分钟发出提示
        Date.from(appointmentTime.minusMinutes(10).atZone(ZoneId.systemDefault()).toInstant()));

        // 开启线程等待预约时间到了再结束线程
        CACHE_REBUILD_EXECUTOR.submit(()->{
            while (true) {
                if (LocalDateTime.now().isAfter(appointmentTime)) {
                    //使用时间到，关闭用电开关
                    System.out.println("使用时间到，关闭用电开关");
                    timer.cancel();
                    break;
                }
                try {
                    Thread.sleep(1000); // 每隔1秒钟检查一次
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
                });

    }


}
